import {Injectable} from '@angular/core';
import {Util} from "@providers/util";
import {WechatJsSdkProvider} from "@providers/wechat-js-sdk";
import {Platform} from "ionic-angular";
import {ImagePickerObject} from "@common/ImagePickerObject";
import {ImagePicker} from '@ionic-native/image-picker';

/*
  Generated class for the NativePickerProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NativePickerProvider {

  constructor(private wechat: WechatJsSdkProvider,
              private imagePicker: ImagePicker,
              private platform: Platform) {
  }

  /**
   * 图片选择控件
   */
  choose(options): Promise<ImagePickerObject[]> {
    options["max"] == 0 && delete options["max"];
    let arr: ImagePickerObject[] = [];
    return new Promise<ImagePickerObject[]>((resolve, reject) => {
      if (this.platform.is("cordova")) {
        //这个鬼插件没有权限时会闪退
        this.imagePicker.hasReadPermission().then(flag => {
          if (!flag) {
            //如果没有权限 则请求权限
            this.imagePicker.requestReadPermission();
          } else {
            this.imagePicker.getPictures({
              width: 800,
              height: 800,
              quality: 25,
              outputType: 1,
              maximumImagesCount: options["max"]
            }).then((files) => {
              if (Util.isNull(files)) return;

              for (let i = 0; i < files.length; i++) {
                let file = files[i];
                let base64 = 'data:image/png;base64,' + file;
                arr.push({type: 'cordova', base64: base64, url: file});
              }
              resolve(arr);
            }, (err) => {
              console.log("err:" + err);
            });
          }
        });

      } else if (this.wechat.isWechat()) {
        this.wechat.chooseImage({
          count: options["max"] || 5,
          sizeType: ['original', 'compressed'],
          sourceType: ['album'],
        }).then((res) => {
          res = res['localIds'];
          if (Util.isNull(res)) return;
          if (res.length == 0) {
            return;
          }
          for (let i = 0; i < res.length; i++) {
            let localId = res[i];
            this.wechat.getLocalImgData(localId)
              .then(localData => {
                arr.push({type: 'Wechat', base64: localData, url: localData});
                if (i == (res.length - 1)) resolve(arr);
              });
          }
        }, (err) => {
        });
      } else {
        let input = document.createElement("input");
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.setAttribute('multiple', 'multiple');
        input.addEventListener('change', (e) => {
          let files = input.files;
          if (Util.isNull(files)) return;
          for (let i = 0; i < files.length; i++) {
            let file = files[i];
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
              let base64 = this.result;
              arr.push({type: 'h5', base64: base64, url: base64});
              if (i == (files.length - 1)) resolve(arr);
            }
          }
        });
        input.click();
      }
    })
  }

}
